package com.cupdata.marathon.exception;

import com.cupdata.marathon.definition.DownRslt;
import com.cupdata.marathon.definition.MemTp;
import com.cupdata.marathon.definition.RspCd;
import com.cupdata.marathon.param.download.DownloadRequest;
import com.cupdata.marathon.param.download.DownloadResponse;
import com.cupdata.marathon.service.ITblHackCouponDownTransLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    ITblHackCouponDownTransLogService couponDownTransLogService;

    /**
     * 要拦截的异常Exception
     */
    @ExceptionHandler(BindException.class)
    public DownloadResponse parameterExceptionHandler(BindException e) {
        DownloadResponse response = new DownloadResponse();
        response.setRspCd(RspCd.SUCCESS.getCode());

        BindingResult bindingResult = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            StringBuilder msg = new StringBuilder();

            for (ObjectError error : errors) {
                msg.append(", ");
                if (error instanceof FieldError) {
                    msg.append(((FieldError) error).getField()).append(": ");
                }
                msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());

            }
            response.setRspMsg(msg.substring(2));
        }

        DownloadRequest request = (DownloadRequest) bindingResult.getTarget();
        response.setTransId(request.getTransId());
        response.setDownRslt(DownRslt.R800099.getCode());
        response.setMemTp(MemTp.NON_MEMBER.getCode());

        couponDownTransLogService.save(request, response, LocalDateTime.now());

        return response;
    }

    @ExceptionHandler(Exception.class)
    public String commonHandler(Exception e) {
        return "999999";
    }


}